package com.dingreading.cloud.app.controller;

import com.dingreading.cloud.app.entity.Books;
import com.dingreading.cloud.app.entity.Corporations;
import com.dingreading.cloud.app.entity.Staff;
import com.dingreading.cloud.app.entity.StoreBooks;
import com.dingreading.cloud.app.service.BooksService;
import com.dingreading.cloud.app.service.CorporationsService;
import com.dingreading.cloud.app.service.StoreBooksService;
import com.dingreading.cloud.app.util.BooksUtil;
import com.dingreading.cloud.app.util.UidUtil;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.BookSimpleDto;
import com.dingreading.cloud.common.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/app/storeBooks")
@Api(tags = "门店-门店书籍管理相关")
public class AppStoreBooksController {

    @Resource
    private CorporationsService corporationsService;
    @Resource
    private BooksService booksService;
    @Resource
    private StoreBooksService storeBooksService;

    @ApiOperation(value = "判断是否能添加书籍")
    @PostMapping(value = "/whetherAddBook", produces = "application/json; charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public R<Object> whetherAddBook(
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "isbn/书号") @RequestParam(value = "isbn") String isbn
    ) {
//        Object staffObj = UidUtil.getStaff(staffUid);
//        if (staffObj instanceof String) return R.fail(staffObj.toString());
//        Staff staff = (Staff) staffObj;
//
//        if (isbn.length() != 13 && isbn.length() != 8) return R.fail("isbn号或书号异常");
//
//        List<BookSimpleDto> list = new ArrayList<>();
//
//        // 判断门店书籍，相同的isbn和书号
//        List<Long> bookIds = null;
//        List<StoreBooks> storeBookAndList = storeBooksService.getByStoreIdAndIsbnOrBookNum(staff.getStoreId(), isbn);
//        if (CollectionUtils.isNotEmpty(storeBookAndList)) {
//            List<BookSimpleDto> bookSimpleList = BooksUtil.getBookSimpleDtoByStoreBook(storeBookAndList);
//            list.addAll(bookSimpleList);
//
//            bookIds = bookSimpleList.stream()
//                    .filter(bookSimpleDto -> bookSimpleDto.getBooksId() != null)
//                    .map(BookSimpleDto::getBooksId).collect(Collectors.toList());
//        }
//
//        // 判断系统书籍，相同的isbn和书号
//        List<Books> booksList = booksService.getByIsbnOrBookNumNotInId(isbn, bookIds);
//        if (CollectionUtils.isNotEmpty(booksList)) {
//            List<BookSimpleDto> bookSimpleList = BooksUtil.getBookSimpleDto(booksList);
//            list.addAll(bookSimpleList);
//        }
//
//        if (CollectionUtils.isNotEmpty(list)) {
//            return R.fail(4001, "发现相同isbn的书籍", list);
//        }
//
//        return R.ok();
        return R.fail("功能已暂停，请升级App版本");
    }

    @ApiOperation(value = "将书籍添加到门店（系统书籍优先添加）")
    @PostMapping(value = "/bookAddToStore", produces = "application/json; charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public R<Object> bookAddToStore(
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "书籍id") @RequestParam(value = "bookId") Long bookId
    ) {
//        Object staffObj = UidUtil.getStaff(staffUid);
//        if (staffObj instanceof String) return R.fail(staffObj.toString());
//        Staff staff = (Staff) staffObj;
//
//        Books books = booksService.getById(bookId);
//        if (books == null) {
//            return R.fail("书籍获取失败");
//        }
//
//        List<StoreBooks> storeBooksList = storeBooksService.getByStoreIdAndBooksId(staff.getStoreId(), bookId);
//        if (CollectionUtils.isNotEmpty(storeBooksList)) return R.fail("门店不能重复导入这本书");
//
//        StoreBooks storeBooks = BooksUtil.newStoreBooks(books, staff.getStoreId(), DateUtil.getNowDatetime(), books.getSource());
//        storeBooksService.saveOrUpdate(storeBooks);
//
//        BookSimpleDto bookSimpleDto = BooksUtil.newBookSimpleDto(storeBooks.getBooksId(), storeBooks.getId(), 1,
//                1, storeBooks.getIsbn(), storeBooks.getBookNum(), storeBooks.getBookName(), storeBooks.getAuthor(),
//                storeBooks.getBookLabelId(), storeBooks.getBookLabelName(), books.getBookType());
//        return R.ok(bookSimpleDto);
        return R.fail("功能已暂停，请升级App版本");
    }

    @ApiOperation(value = "书籍库存数量加1")
    @PostMapping(value = "/addStockNum", produces = "application/json; charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public R<Object> addStockNum(
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "门店书籍id") @RequestParam(value = "storeBookId") Long storeBookId,
            @ApiParam(value = "数量") @RequestParam(value = "num", required = false) Integer num
    ) {
//        Object staffObj = UidUtil.getStaff(staffUid);
//        if (staffObj instanceof String) return R.fail(staffObj.toString());
//        Staff staff = (Staff) staffObj;
//
//        StoreBooks storeBooks = storeBooksService.getByStoreIdAndId(staff.getStoreId(), storeBookId);
//        if (storeBooks == null) {
//            return R.fail("书籍获取失败");
//        } else {
//            storeBooksService.updateStockNum(storeBookId, num);
//        }
//
//        return R.ok();
        return R.fail("功能已暂停，请升级App版本");
    }

    @ApiOperation(value = "判断是否能添加书籍")
    @PostMapping(value = "/v2/whetherAddBook", produces = "application/json; charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public R<Object> whetherAddBookV2(
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "isbn/书号") @RequestParam(value = "isbn") String isbn
    ) {
        Object store = UidUtil.getStore(storeUid);
        if (store instanceof String)
            return R.fail(store.toString());

        Object staffObj = UidUtil.getStaff(staffUid);
        if (staffObj instanceof String) return R.fail(staffObj.toString());
        Staff staff = (Staff) staffObj;

        Corporations corporations = corporationsService.getByUid(staff.getCorpUid());
        String judgeCorp = UidUtil.judgeCorp(corporations);
        if (StringUtils.isNotBlank(judgeCorp))
            return R.fail(judgeCorp);

        if (isbn.length() != 13 && isbn.length() != 8) return R.fail("isbn号或书号异常");

        List<BookSimpleDto> list = new ArrayList<>();

        // 判断门店书籍，相同的isbn和书号
        List<Long> bookIds = null;
        List<StoreBooks> storeBookAndList = storeBooksService.getByStoreIdAndIsbnOrBookNum(staff.getStoreId(), isbn);
        if (CollectionUtils.isNotEmpty(storeBookAndList)) {
            List<BookSimpleDto> bookSimpleList = BooksUtil.getBookSimpleDtoByStoreBook(storeBookAndList);
            list.addAll(bookSimpleList);

            bookIds = bookSimpleList.stream()
                    .filter(bookSimpleDto -> bookSimpleDto.getBooksId() != null)
                    .map(BookSimpleDto::getBooksId).collect(Collectors.toList());
        }

        // 判断系统书籍，相同的isbn和书号
        List<Books> booksList = booksService.getByIsbnOrBookNumNotInId(isbn, bookIds);
        if (CollectionUtils.isNotEmpty(booksList)) {
            List<BookSimpleDto> bookSimpleList = BooksUtil.getBookSimpleDto(booksList);
            list.addAll(bookSimpleList);
        }

        if (CollectionUtils.isNotEmpty(list)) {
            return R.fail(4001, "发现相同isbn的书籍", list);
        }

        return R.ok();
    }

    @ApiOperation(value = "将书籍添加到门店（系统书籍优先添加）")
    @PostMapping(value = "/v2/bookAddToStore", produces = "application/json; charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public R<Object> bookAddToStoreV2(
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "书籍id") @RequestParam(value = "bookId") Long bookId
    ) {
        Object store = UidUtil.getStore(storeUid);
        if (store instanceof String)
            return R.fail(store.toString());

        Object staffObj = UidUtil.getStaff(staffUid);
        if (staffObj instanceof String) return R.fail(staffObj.toString());
        Staff staff = (Staff) staffObj;

        Corporations corporations = corporationsService.getByUid(staff.getCorpUid());
        String judgeCorp = UidUtil.judgeCorp(corporations);
        if (StringUtils.isNotBlank(judgeCorp))
            return R.fail(judgeCorp);

        Books books = booksService.getById(bookId);
        if (books == null) {
            return R.fail("书籍获取失败");
        }

        List<StoreBooks> storeBooksList = storeBooksService.getByStoreIdAndBooksId(staff.getStoreId(), bookId);
        if (CollectionUtils.isNotEmpty(storeBooksList)) return R.fail("门店不能重复导入这本书");

        StoreBooks storeBooks = BooksUtil.newStoreBooks(books, staff.getStoreId(), DateUtil.getNowDatetime(), books.getSource());
        storeBooksService.saveOrUpdate(storeBooks);

        BookSimpleDto bookSimpleDto = BooksUtil.newBookSimpleDto(storeBooks.getBooksId(), storeBooks.getId(), 1,
                1, storeBooks.getIsbn(), storeBooks.getBookNum(), storeBooks.getBookName(), storeBooks.getAuthor(),
                storeBooks.getBookLabelId(), storeBooks.getBookLabelName(), books.getBookType());
        return R.ok(bookSimpleDto);
    }

    @ApiOperation(value = "书籍库存数量加1")
    @PostMapping(value = "/v2/addStockNum", produces = "application/json; charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public R<Object> addStockNumV2(
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "门店书籍id") @RequestParam(value = "storeBookId") Long storeBookId,
            @ApiParam(value = "数量") @RequestParam(value = "num", required = false) Integer num
    ) {
        Object store = UidUtil.getStore(storeUid);
        if (store instanceof String)
            return R.fail(store.toString());

        Object staffObj = UidUtil.getStaff(staffUid);
        if (staffObj instanceof String) return R.fail(staffObj.toString());
        Staff staff = (Staff) staffObj;

        Corporations corporations = corporationsService.getByUid(staff.getCorpUid());
        String judgeCorp = UidUtil.judgeCorp(corporations);
        if (StringUtils.isNotBlank(judgeCorp))
            return R.fail(judgeCorp);

        StoreBooks storeBooks = storeBooksService.getByStoreIdAndId(staff.getStoreId(), storeBookId);
        if (storeBooks == null) {
            return R.fail("书籍获取失败");
        } else {
            storeBooksService.updateStockNum(storeBookId, num);
        }

        return R.ok();
    }

}
